package com.frame.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.frame.Page;
import com.frame.domain.Menu;
import com.frame.support.Tree;
import com.mini.core.PageResult;
import com.mini.core.dao.MiniDao;
import com.mini.core.utils.StrKit;

/**
 * @author sxjun
 * @version 2016-6-02
 */
@Service
public class MenuService{

	@Autowired
	MiniDao miniDao;
	
	/**
	 * 查找所有菜单
	 * @return
	 */
	public List<Menu> findAll(){
		String sql = "SELECT * FROM MENU";
		return miniDao.findList(sql, Menu.class);
	}
	
	/**
	 * 分页查询用户
	 * @param page
	 * @param treeId
	 * @return
	 */
	public Page<Menu> paginateResult(Page<Menu> page,String treeId){
		String sql = "SELECT * FROM MENU WHERE 1=1";
		PageResult<Menu> menus = null;
		if(StrKit.notBlank(treeId) && !Tree.TREE_ROOT_ID.equals(treeId)){
			sql+=" AND (PARENTID=? OR ID =?)";
			menus = miniDao.paginateResult(sql, page.getPageNo(), page.getPageSize(), Menu.class,treeId,treeId);
		}else
			menus = miniDao.paginateResult(sql, page.getPageNo(), page.getPageSize(), Menu.class);
		page.setPageResult(menus);
		return page;
	}

	/**
	 * 插入数据
	 * @param menu
	 */
	public void save(Menu menu) {
		miniDao.insert(menu);
	}
	
	/**
	 * 更新数据
	 * @param menu
	 */
	public void update(Menu menu) {
		miniDao.update(menu);
	}
	
	/**
	 * 根据Id删除菜单
	 * @param id
	 */
	public void delete(String id){
		miniDao.deleteById(Menu.class, id);
	}

	/**
	 * 获取菜单
	 * @param id
	 * @return
	 */
	public Menu findById(String id) {
		return miniDao.findById(Menu.class, id);
	}

	/**
	 * 根据用户账号获取菜单权限
	 * @param email
	 * @return
	 */
	public List<Menu> findMenuByEmail(String email) {
		return miniDao.findList("SELECT DISTINCT m.* FROM MENU m "
			+" INNER JOIN MENU_PERMISSION mp "
			+" ON mp.MENUID = m.ID "
			+" INNER JOIN PERMISSION p "
			+" ON mp.PERMISSIONID=p.ID "
			+" INNER JOIN ROLE_PERMISSION rp "
			+" ON  p.ID=rp.PERMISSIONID "
			+" INNER JOIN USER_ROLE ur "
			+" ON rp.ROLEID=ur.ROLEID "
			+" INNER JOIN USERS u "
			+" ON ur.USERID=u.ID "
			+" WHERE u.EMAIL=? ORDER BY m.SORT", Menu.class, email);
	}
	
}
